package com.njtoyo.taxi.admin.service.local_service.commodity.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.dynamic.datasource.annotation.DSTransactional;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.njtoyo.taxi.admin.library.common.OperationRecordHelper;
import com.njtoyo.taxi.admin.mapper.master.entity.local_service.*;
import com.njtoyo.taxi.admin.mapper.master.enums.local_service.LifeCommodityExchangeType;
import com.njtoyo.taxi.admin.mapper.master.enums.local_service.LifeMerchantCommodityState;
import com.njtoyo.taxi.admin.mapper.master.mapper.local_service.*;
import com.njtoyo.taxi.admin.rest.presenter.local_service.commodity.CommodityDetailsPresenter;
import com.njtoyo.taxi.admin.rest.presenter.local_service.commodity.CommodityPagePresenter;
import com.njtoyo.taxi.admin.rest.wrapper.local_service.commodity.CommodityAddWrapper;
import com.njtoyo.taxi.admin.rest.wrapper.local_service.commodity.CommodityBatchUpdateWrapper;
import com.njtoyo.taxi.admin.rest.wrapper.local_service.commodity.CommodityPageWrapper;
import com.njtoyo.taxi.admin.rest.wrapper.local_service.commodity.CommodityUpdateWrapper;
import com.njtoyo.taxi.admin.service.local_service.commodity.CommodityService;
import com.njtoyo.taxi.entity.backend.AdminUser;
import com.taxi.entity.common.RestResult;
import com.taxi.entity.common.ResultEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.hutool.core.bean.BeanUtil.copyProperties;
import static cn.hutool.core.util.ObjectUtil.isEmpty;
import static cn.hutool.core.util.ObjectUtil.isNotEmpty;

@Slf4j
@Service
public class CommodityServiceImpl implements CommodityService {

    @Autowired
    private OperationRecordHelper operationRecordHelper;

    @Autowired
    private LifeMerchantCommodityMapper lifeMerchantCommodityMapper;

    @Autowired
    private LifeMerchantMapper lifeMerchantMapper;

    @Autowired
    private LifeMerchantCommodityCategoryMapper lifeMerchantCommodityCategoryMapper;

    @Autowired
    private LifeMerchantCommodityRegionMappingMapper lifeMerchantCommodityRegionMapper;

    @Autowired
    private LifeMerchantMemberOrderMapper orderMapper;

    @Autowired
    private LifeMerchantCommodityRegionMappingMapper commodityRegionMappingMapper;

    @Autowired
    private LifeDriverRegionCommodityMappingMapper lifeDriverRegionCommodityMappingMapper;


    /**
     * 所有商品
     *
     * @return
     */
    @Override
    public RestResult<List<LifeMerchantCommodity>> all() {
        QueryWrapper<LifeMerchantCommodity> wrapper = new QueryWrapper<>();
        wrapper.select("id", "name", "merchant_id", "commodity_category_id");
        List<LifeMerchantCommodity> list = lifeMerchantCommodityMapper.selectList(wrapper);
        return RestResult.success(list);
    }

    /**
     * 商户下所有商品
     *
     * @param merchantId
     * @return
     */
    @Override
    public RestResult<List<LifeMerchantCommodity>> allByMerchantId(Long  merchantId) {
        QueryWrapper<LifeMerchantCommodity> wrapper = new QueryWrapper<>();
        wrapper.in("merchant_id", merchantId);
        wrapper.in("is_presented", true);
        List<LifeMerchantCommodity> list = lifeMerchantCommodityMapper.selectList(wrapper);
        List<LifeMerchantCommodity> result =new ArrayList<>();
        /**
         * 商品可以售卖{
         *     有库存,时间未过期,已经上架on_shelf
         * }
         */
        list.forEach(results -> {
            LifeMerchantCommodityState state = results.getState();
            Integer store = results.getStore();
            Date endedAt = results.getEndedAt();
            Date startedAt = results.getStartedAt();
            Date date = new Date();
            if (LifeMerchantCommodityState.on_shelf.equals(state) && store > 0 &&
                    //过期时间之前,开始时间之后
                    date.before(endedAt) && date.after(startedAt)) {
                result.add(results);
            }
        });
        return RestResult.success(result);
    }

    /**
     * 商品列表
     *
     * @param adminUser
     * @param wrapper
     * @return
     */
    @Override
    public RestResult<Page<CommodityPagePresenter>> getPage(AdminUser adminUser, CommodityPageWrapper wrapper) {
        switch (adminUser.getAccountType()) {
            case platform:
                break;
            default:
                return RestResult.failed("账号权限不够");
        }
        Page<CommodityPagePresenter> page = lifeMerchantCommodityMapper.getPage(wrapper);
        List<CommodityPagePresenter> list = page.getRecords();
        if (isNotEmpty(list)) {

            List<Long> merchantIds = list.stream().map(CommodityPagePresenter::getMerchantId).collect(Collectors.toList());
            List<Long> commodityCategoryId = list.stream().map(CommodityPagePresenter::getCommodityCategoryId).collect(Collectors.toList());

            //商家名称
            QueryWrapper<LifeMerchant> lifeMerchantWrapper = new QueryWrapper<>();
            lifeMerchantWrapper.select("id", "name");
            lifeMerchantWrapper.in("id", merchantIds);
            List<Map<String, Object>> maps = lifeMerchantMapper.selectMaps(lifeMerchantWrapper);
            Map<Long, String> map = maps.stream().collect(Collectors.toMap(i -> Long.valueOf(i.get("id").toString()), i -> i.get("name").toString()));

            //商品分类类型
            QueryWrapper<LifeMerchantCommodityCategory> CommodityCategoryWrapper = new QueryWrapper<>();
            CommodityCategoryWrapper.select("id", "name");
            CommodityCategoryWrapper.in("id", commodityCategoryId);
            List<Map<String, Object>> maps1 = lifeMerchantCommodityCategoryMapper.selectMaps(CommodityCategoryWrapper);
            Map<Long, String> map1 = maps1.stream().collect(Collectors.toMap(i -> Long.valueOf(i.get("id").toString()), i -> i.get("name").toString()));

            list.forEach(commodityPagePresenter -> {
                commodityPagePresenter.setMerchantName(map.getOrDefault(commodityPagePresenter.getMerchantId(), null));
                commodityPagePresenter.setCommodityCategoryName(map1.getOrDefault(commodityPagePresenter.getCommodityCategoryId(), null));
            });
            /**
             * 商品可以售卖{
             *     有库存,时间未过期,已经上架on_shelf
             * }
             */
            list.forEach(result -> {
                LifeMerchantCommodityState state = result.getState();
                Integer store = result.getStore();
                Date endedAt = result.getEndedAt();
                Date startedAt = result.getStartedAt();
                Date date = new Date();
                if (LifeMerchantCommodityState.on_shelf.equals(state) && store > 0 &&
                        //过期时间之前,开始时间之后
                        date.before(endedAt) && date.after(startedAt)) {
                    result.setIsSell(true);
                } else {
                    result.setIsSell(false);
                }
            });
        }
        return RestResult.success(page);
    }

    /**
     * 商品详情
     *
     * @param id
     * @return
     */
    @Override
    public RestResult<CommodityDetailsPresenter> details(Long id) {
        LifeMerchantCommodity lifeMerchantCommodity = lifeMerchantCommodityMapper.selectById(id);
        if (isEmpty(lifeMerchantCommodity)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }
        CommodityDetailsPresenter result =
                copyProperties(lifeMerchantCommodity, CommodityDetailsPresenter.class);

        if (isNotEmpty(result)) {
            Long merchantId = result.getMerchantId();
            Long commodityCategoryId = result.getCommodityCategoryId();

            //商家名称
            QueryWrapper<LifeMerchant> lifeMerchantWrapper = new QueryWrapper<>();
            lifeMerchantWrapper.select("id", "name");
            lifeMerchantWrapper.eq("id", merchantId);
            LifeMerchant lifeMerchant = lifeMerchantMapper.selectOne(lifeMerchantWrapper);
            if (isNotEmpty(lifeMerchant)) {
                result.setMerchantName(lifeMerchant.getName());
            }

            //商品分类类型
            QueryWrapper<LifeMerchantCommodityCategory> CommodityCategoryWrapper = new QueryWrapper<>();
            CommodityCategoryWrapper.select("id", "name");
            CommodityCategoryWrapper.in("id", commodityCategoryId);
            LifeMerchantCommodityCategory lifeMerchantCommodityCategory = lifeMerchantCommodityCategoryMapper.selectOne(CommodityCategoryWrapper);
            if (isNotEmpty(lifeMerchantCommodityCategory)) {
                result.setCommodityCategoryName(lifeMerchantCommodityCategory.getName());
            }
        }

        return RestResult.success(result);
    }


    /**
     * 添加商品
     *
     * @param wrapper
     * @return
     */
    @Override
    @DSTransactional
    public RestResult add(CommodityAddWrapper wrapper) throws ParseException {
        //商家,类型是否存在
        Long merchantId = wrapper.getMerchantId();
        Long commodityCategoryId = wrapper.getCommodityCategoryId();
        BigDecimal proportion = wrapper.getProportion();
        if (proportion.compareTo(BigDecimal.valueOf(100)) == 1) {
            return RestResult.failed("分润比例不能大于100%");
        }

        LifeMerchant lifeMerchant = lifeMerchantMapper.selectById(merchantId);
        LifeMerchantCommodityCategory lifeMerchantCommodityCategory =
                lifeMerchantCommodityCategoryMapper.selectById(commodityCategoryId);
        if (isEmpty(lifeMerchant)) {
            return RestResult.failed("商家不存在");
        } else if (isEmpty(lifeMerchantCommodityCategory)) {
            return RestResult.failed("商品类型不存在");
        } else if (LifeCommodityExchangeType.coupon.equals(lifeMerchantCommodityCategory.getCommodityExchangeType())
                && isEmpty(wrapper.getTemplate())) {
            return RestResult.failed("商品兑换类型需要配优惠券模板");
        }

        //接口的结束时间，加上 23:59:59
        String start = wrapper.getStartedAt();
        String end = wrapper.getEndedAt();
        String startTime = start + " 00:00:00";
        String endTime = end + " 23:59:59";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//注意月份是MM
        Date startDate = simpleDateFormat.parse(startTime);
        Date endDate = simpleDateFormat.parse(endTime);

        //添加商品
        LifeMerchantCommodity lifeMerchantCommodity = copyProperties(wrapper, LifeMerchantCommodity.class);
        lifeMerchantCommodity.setStartedAt(startDate);
        lifeMerchantCommodity.setEndedAt(endDate);
        lifeMerchantCommodity.setSalesCount(0);
        lifeMerchantCommodity.setVerificationCount(0);
        //商品是否自提通过优惠券和兑换物区分
        if (commodityCategoryId == 2) {
            lifeMerchantCommodity.setToPickUpLocation(false);
        } else {
            lifeMerchantCommodity.setToPickUpLocation(true);
        }

        if (isNotEmpty(lifeMerchantCommodity)) {
            lifeMerchantCommodity.setTemplate(JSONUtil.toJsonStr(wrapper.getTemplate()));
        }
        lifeMerchantCommodityMapper.insert(lifeMerchantCommodity);
        Long id = lifeMerchantCommodity.getId();

        //关联区域
        Long regionId = lifeMerchant.getMerchantRegionId();
        LifeMerchantCommodityRegionMapping lifeMerchantCommodityRegionMapping = new LifeMerchantCommodityRegionMapping();
        lifeMerchantCommodityRegionMapping.setMerchantCommodityId(id);
        lifeMerchantCommodityRegionMapping.setRegionId(regionId);
        lifeMerchantCommodityRegionMapper.insert(lifeMerchantCommodityRegionMapping);

        operationRecordHelper.addBusinessLog(String.format("新增了商品 [%d] 的信息", id));
        return RestResult.success();
    }

    /**
     * 修改商品
     *
     * @param id
     * @param wrapper
     * @return
     */
    @Override
    @DSTransactional
    public RestResult update(Long id, CommodityUpdateWrapper wrapper) throws ParseException {
        LifeMerchantCommodity lifeMerchantCommodity = lifeMerchantCommodityMapper.selectById(id);
        if (isEmpty(lifeMerchantCommodity)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }

        //接口的结束时间，加上 23:59:59
        String start = wrapper.getStartedAt();
        String end = wrapper.getEndedAt();
        String startTime = start + " 00:00:00";
        String endTime = end + " 23:59:59";
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//注意月份是MM
        Date startDate = simpleDateFormat.parse(startTime);
        Date endDate = simpleDateFormat.parse(endTime);

        //商品存在关联关系无法删除
        QueryWrapper<LifeDriverRegionCommodityMapping> regionCommodityMappingQueryWrapper = new QueryWrapper<>();
        regionCommodityMappingQueryWrapper.eq("commodity_id", id);
        Integer count = lifeDriverRegionCommodityMappingMapper.selectCount(regionCommodityMappingQueryWrapper);
        if (count > 0) {
            return RestResult.failed("商品存在关联关系无法修改");
        }

        new LambdaUpdateChainWrapper<>(lifeMerchantCommodityMapper)
                .eq(LifeMerchantCommodity::getId, id)
                .set(LifeMerchantCommodity::getState, wrapper.getState())
                .set(LifeMerchantCommodity::getName, wrapper.getName())
                .set(LifeMerchantCommodity::getTitle, wrapper.getTitle())
                .set(LifeMerchantCommodity::getProportion, wrapper.getProportion())
                .set(LifeMerchantCommodity::getUnitPrice, wrapper.getUnitPrice())
                .set(LifeMerchantCommodity::getOriginalCost, wrapper.getOriginalCost())
                .set(LifeMerchantCommodity::getShareProfitPrice, wrapper.getShareProfitPrice())
                .set(LifeMerchantCommodity::getUnitPoint, wrapper.getUnitPoint())
                .set(LifeMerchantCommodity::getStore, wrapper.getStore())
                .set(LifeMerchantCommodity::getStartedAt, startDate)
                .set(LifeMerchantCommodity::getEndedAt, endDate)
                .set(LifeMerchantCommodity::getSortBy, wrapper.getSortBy())
                .set(LifeMerchantCommodity::getTemplate, JSONUtil.toJsonStr(wrapper.getTemplate()))
                .set(LifeMerchantCommodity::getDeadlineDay, wrapper.getDeadlineDay())
                .set(LifeMerchantCommodity::getIconImageUrl, wrapper.getIconImageUrl())
                .set(LifeMerchantCommodity::getDetails, wrapper.getDetails())
                .set(LifeMerchantCommodity::getIsPresented, wrapper.getIsPresented())
                .set(LifeMerchantCommodity::getUpdatedAt, new Date())
                .update();

        //修改区域关联 ->商户运营区变,商品运营区不变
        //LifeMerchant lifeMerchant = lifeMerchantMapper.selectById(lifeMerchantCommodity.getMerchantId());
        //Long regionId = lifeMerchant.getMerchantRegionId();
        //new LambdaUpdateChainWrapper<>(lifeMerchantCommodityRegionMapper)
        //        .eq(LifeMerchantCommodityRegionMapping::getMerchantCommodityId, id)
        //        .set(LifeMerchantCommodityRegionMapping::getRegionId, regionId)
        //        .set(LifeMerchantCommodityRegionMapping::getUpdatedAt, new Date())
        //        .update();
        operationRecordHelper.addBusinessLog(String.format("修改了商品 [%d] 的信息", id));
        return RestResult.success();
    }

    /**
     * 删除商品
     *
     * @param id
     * @return
     */
    @Override
    public RestResult delete(Long id) {
        LifeMerchantCommodity lifeMerchantCommodity = lifeMerchantCommodityMapper.selectById(id);
        if (isEmpty(lifeMerchantCommodity)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }

        //存在订单,无法删除
        QueryWrapper<LifeMerchantMemberOrder> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("merchant_commodity_id", id);
        Integer count1 = orderMapper.selectCount(orderQueryWrapper);
        if (count1 > 0) {
            return RestResult.failed("商品存在订单");
        }

        //商品存在关联关系无法删除
        QueryWrapper<LifeDriverRegionCommodityMapping> regionCommodityMappingQueryWrapper = new QueryWrapper<>();
        regionCommodityMappingQueryWrapper.eq("commodity_id", id);
        Integer count2 = lifeDriverRegionCommodityMappingMapper.selectCount(regionCommodityMappingQueryWrapper);
        if (count2 > 0) {
            return RestResult.failed("商品存在关联关系无法删除");
        }

        //删除商品展示区域
        QueryWrapper<LifeMerchantCommodityRegionMapping> wrapper = new QueryWrapper<>();
        wrapper.eq("merchant_commodity_id", id);
        commodityRegionMappingMapper.delete(wrapper);

        operationRecordHelper.addBusinessLog(String.format("删除了商品 [%d] 的信息", id));
        return RestResult.success();
    }

    /**
     * 批量操作商品状态
     *
     * @param wrapper
     * @return
     */
    @Override
    public RestResult updateBatch(CommodityBatchUpdateWrapper wrapper) {
        List<Long> ids = wrapper.getIds();
        if (isEmpty(ids)) {
            return RestResult.build(ResultEnum.NOT_FOUND);
        }

        ids.forEach(id -> {
            LifeMerchantCommodity lifeMerchantCommodity = lifeMerchantCommodityMapper.selectById(id);
            if (isNotEmpty(lifeMerchantCommodity)) {
                new LambdaUpdateChainWrapper<>(lifeMerchantCommodityMapper)
                        .eq(LifeMerchantCommodity::getId, id)
                        .set(LifeMerchantCommodity::getState, wrapper.getState())
                        .set(LifeMerchantCommodity::getUpdatedAt, new Date())
                        .update();
                operationRecordHelper.addBusinessLog(String.format("修改了商品 [%d] 的信息", id));
            }
        });
        return RestResult.success();
    }


}
